package handlers

import (
	"encoding/json"
	"strconv"
	"strings"

	"github.com/RuiGuangServer/config"
	"github.com/RuiGuangServer/global"
	"github.com/RuiGuangServer/logs"
	"github.com/RuiGuangServer/utils"
)

type Awos struct {
	TYPE string     `json:"TYPE"` // 数据类型，如 "VIS"
	LOC  string     `json:"LOC"`  // 位置标识，如 "36R"
	DATA [][]string `json:"DATA"` // 数据数组，每个元素是一个字符串数组
	TIME int64      `json:"TIME"` // 时间戳
	AP   string     `json:"AP"`   // 机场代码，如 "ZGHA"
}

func HandleAWOS(data []byte, logger *logs.AsyncLogger, dataer *logs.AsyncLogger) {
	dataer.Data("zstd压缩后的数据[AWOS_receive]: %v", data)
	awosjson, err := parsingAwos(data)
	if err != nil {
		logger.Warn("%v", err)
	}
	dataer.Data("zstd解压后的数据[AWOS_receive]: %+v\n", awosjson)

	if awosjson.TYPE == "" {
		logger.Warn("Received awos with nil data")
		return
	}

	AwosAP := awosjson.AP
	if AwosAP != config.Config.AirPort {
		logger.Info("Flight schedules for non %v airports", config.Config.AirPort)
		return
	}

	// 获取或创建机场状态
	state, _ := global.CurrentAirPortState.LoadOrStore(AwosAP, &global.AirPortState{
		AirPort: AwosAP,
		Vis:     0,
		Cloud:   0,
		Rvr:     0,
		Vis1A:   0,
		RWY:     "",
		Oper:    0,
	})
	currentState := state.(*global.AirPortState)

	switch awosjson.TYPE {
	case "VIS":
		processVisibilityData(awosjson.DATA, currentState)
	case "RWY":
		processRunwayData(awosjson.DATA, currentState, config.Config.RunWayNum)
	}
	currentState.Oper = 1
}

// parsingAwos 解析自观数据
func parsingAwos(data []byte) (Awos, error) {
	var awosjson Awos
	jsonByte, err := utils.ZstdToJson(data)
	if err != nil {
		return awosjson, err
	}
	// fmt.Printf("decompressed :%v\n", decompressed)
	if err := json.Unmarshal(jsonByte, &awosjson); err != nil {
		return awosjson, err
	}
	return awosjson, nil
}

// processVisibilityData 缓存Rvr，VIS1A
func processVisibilityData(data [][]string, state *global.AirPortState) {
	isoper := false
	for _, item := range data {
		if len(item) != 4 {
			continue
		}

		key, value := item[0], item[3]
		switch key {
		case "RVR1A":
			if v, err := strconv.ParseInt(value, 10, 64); err == nil {
				state.Rvr = v
				isoper = true
			}
		case "VIS1A":
			if v, err := strconv.ParseInt(value, 10, 64); err == nil {
				state.Vis1A = v
				isoper = true
			}
		}
	}
	if isoper && state.Oper == 0 {
		state.Oper = 1
	}
}

// processRunwayData 处理跑道数据
func processRunwayData(data [][]string, state *global.AirPortState, RunWayNum int) {
	currentRunway := state.RWY

	for _, item := range data {
		if !(len(item) == 4 && item[0] == "RWY") {
			continue
		}

		runwayValue := item[3]
		if currentRunway == "" {
			updateRunwayState(state, runwayValue, "")
			currentRunway = runwayValue
			continue
		}

		if strings.Contains(currentRunway, runwayValue) {
			continue
		}

		switch RunWayNum {
		case 1:
			updateRunwayState(state, runwayValue, "")
			currentRunway = runwayValue
		case 2:
			runways := strings.Split(currentRunway, ",")
			if len(runways) < 2 {
				updateRunwayState(state, currentRunway, runwayValue)
				currentRunway = state.RWY
			}
		}
	}
}

// updateRunwayState 更新跑道状态
func updateRunwayState(state *global.AirPortState, baseRunway, newRunway string) {
	if newRunway == "" {
		state.RWY = baseRunway
	} else {
		state.RWY = baseRunway + "," + newRunway
	}
}
